package com.job.project.components;

import com.alibaba.fastjson2.JSONObject;
import com.job.project.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author 王博
 * @DateTime 2024-05-24 15:37
 */
@Component
@Slf4j
public class HttpClientUtils {

//    @Value("${third.scheme}")
    private String scheme="https";
//    @Value("${third.host}")
    private String host="api.dingdingzn.com";
//    @Value("${third.port}")
    private Integer port=80;



    /*public  String doGet(String path, Map<String,String> params){
        try {
            List<NameValuePair> pairList = new ArrayList<>(params.size());
            params.forEach((key, value) -> {
                NameValuePair nameValuePair = new BasicNameValuePair(key, value);
                pairList.add(nameValuePair);
            });

            URIBuilder uriBuilder = new URIBuilder();
            uriBuilder.setScheme(scheme).setHost(host).setPort(port).setPath(path).setParameters(pairList);

            HttpGet httpGet = new HttpGet();
            httpGet.setURI(uriBuilder.build());

            HttpResponse httpResponse = httpClient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String response = EntityUtils.toString(httpResponse.getEntity());
                log.info("[Http工具类，get方法]path：{},参数：{},结果{}",path, JSONObject.toJSONString(params),response);
                return response;
            }
            log.info("[Http工具类，get方法]path：{},参数：{},被调用方返回非正常结果:{}",path,JSONObject.toJSONString(params),JSONObject.toJSONString(httpResponse));
            throw   new ServiceException("被调用方返回非正常结果");
        } catch (URISyntaxException | IOException e) {
            log.error("[Http工具类，get方法]path：{},参数：{},调用异常",path, JSONObject.toJSONString(params),e);
            throw new ServiceException("调用第三方失败");
        }
    }*/

    public  String doPost(JSONObject jsonObject) throws Exception{
        // 创建一个允许所有证书的 SSL 上下文
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();

        // 允许所有主机名验证
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                NoopHostnameVerifier.INSTANCE);

        // 创建连接管理器
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
//                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        // 设置连接超时时间
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(cm)
                .build();
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setScheme(scheme).setHost(host).setPath("/kun/mobile/integral/cYouCallback");

        HttpPost httpPost = new HttpPost();
        try {
            httpPost.setURI(uriBuilder.build());
            StringEntity entity = new StringEntity(jsonObject.toJSONString());
            entity.setContentType("application/json");
            httpPost.setEntity(entity);



            HttpResponse httpResponse = httpClient.execute(httpPost);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String response = EntityUtils.toString(httpResponse.getEntity());
                log.info("[Http工具类，post方法],结果{}", response);
                return response;
            }
            log.info("[Http工具类，post方法],被调用方返回非正常结果:{}",JSONObject.toJSONString(httpResponse));
            throw   new ServiceException("被调用方返回非正常结果");
        } catch (URISyntaxException | IOException e) {
            log.error("[Http工具类，post方法]调用异常",e);
            throw new ServiceException("调用第三方失败");
        }finally {
            httpClient.close();
        }
    }
}
